package com.xingkeduo.service.cms.marketing.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.xingkeduo.model.example.TActivityDaysExample;
import com.xingkeduo.model.example.TMarketingCouponExample;
import com.xingkeduo.model.example.TMarketingCouponExample.Criteria;
import com.xingkeduo.model.example.TMarketingRelevantExample;
import com.xingkeduo.model.param.MarketingParam;
import com.xingkeduo.model.param.MarketingParam.MarketingCouponStatusEnum;
import com.xingkeduo.model.param.MarketingParam.MarketingServiceTypeEnum;
import com.xingkeduo.model.param.MarketingParam.MarketingTypeEnum;
import com.xingkeduo.model.po.TActivityDays;
import com.xingkeduo.model.po.TMarketingCouponWithBLOBs;
import com.xingkeduo.model.po.TMarketingRelevant;
import com.xingkeduo.model.vo.ActivityDaysResponseVo;
import com.xingkeduo.model.vo.MarketingResponseVo;
import com.xingkeduo.service.cms.marketing.MarketingTemplateService;
import com.xingkeduo.util.Constant;
import com.xingkeduo.util.DateUtils;
import com.xingkeduo.util.StringUtils;
import com.xingkeduo.util.WeekUtil;
import com.xingkeduo.util.tool.ResponseMessage;

@Service("marketingCouponTemplateService")
public class MarketingCouponTemplateServiceImpl extends MarketingTemplateServiceImpl implements MarketingTemplateService {
	Logger logger = LoggerFactory.getLogger(MarketingCouponTemplateServiceImpl.class);
	@Override
	@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
	public ResponseMessage saveOrUpdateCouponByTemplate(MarketingParam couponTemplate) {
		// 实例化Coupon对象
		TMarketingCouponWithBLOBs coupon = new TMarketingCouponWithBLOBs();
		super.buildMarketing(couponTemplate,coupon);
		// 新券，卡，券包
		if (coupon.getId() == null) {
			coupon.setCreateTime(new Date());
			coupon.setSurplusQuantity(coupon.getStockQuantity());
			tMarketingCouponMapper.insertSelective(coupon);
			couponTemplate.setId(coupon.getId());
			// 增加券，卡与服务关联数据，券包与卡，券关联数据,活动时间
			marketingTemplateService.addTMarketingRelevant(couponTemplate);
			return ResponseMessage.ok(coupon);
		}
		// 老券，卡，券包
		TMarketingCouponWithBLOBs oldTMarketingWith = tMarketingCouponMapper.selectByPrimaryKey(coupon.getId());
		if(oldTMarketingWith.getStockQuantity().intValue()>couponTemplate.getStockQuantity().intValue()) {
			return ResponseMessage.error("库存不能低于初始设置",500);
		}
		if (coupon.getStockQuantity() != null
				&& oldTMarketingWith.getStockQuantity().intValue() != coupon.getStockQuantity().intValue()) {
			coupon.setSurplusQuantity(oldTMarketingWith.getSurplusQuantity().intValue()
					+ coupon.getStockQuantity().intValue() - oldTMarketingWith.getStockQuantity().intValue());
		}
		// 修改服务关联，库存，活动时间
		marketingTemplateService.updateTMarketingRelevant(oldTMarketingWith, couponTemplate);
		tMarketingCouponMapper.updateByPrimaryKeySelective(coupon);
		return ResponseMessage.ok(coupon);
	}


	@Override
	public ResponseMessage queryCouponById(Long couponTemplateId) {
		TMarketingCouponWithBLOBs coupon = tMarketingCouponMapper.selectByPrimaryKey(couponTemplateId);
		if(coupon==null) {
			return ResponseMessage.error("查询券信息失败", 500);
		}
		// 赋值活动时间
		MarketingResponseVo responseVo = new MarketingResponseVo();
		BeanUtils.copyProperties(coupon, responseVo);
		if(StringUtils.isNotBlank(responseVo.getStoreIds())) {
			String storeIds = responseVo.getStoreIds();
			if(storeIds.startsWith("0,")) {
				storeIds = storeIds.substring(2, storeIds.length());
			}
			if(storeIds.endsWith(",0")) {
				storeIds = storeIds.substring(0, storeIds.length()-2);
			}
			responseVo.setStoreIds(storeIds);
		}
		if(coupon.getServiceType().equals(MarketingServiceTypeEnum.DISCOUNT.getType())) {
			responseVo.setCouponAmount(responseVo.getCouponAmount().multiply(BigDecimal.valueOf(10)).setScale(1, BigDecimal.ROUND_HALF_DOWN));
		}
		if (coupon.getMarketingType().intValue() == MarketingTypeEnum.COUPON_BAG.getCode()) {
			TMarketingRelevantExample tMarketingRelevantExample = new TMarketingRelevantExample();
			tMarketingRelevantExample.createCriteria()
									 .andMarketingIdEqualTo(coupon.getId())
									 .andStatusEqualTo(Constant.STATUS_YES)
									 .andTotalQuantityGreaterThan(0);
			List<TMarketingRelevant> relevantList = tMarketingRelevantMapper.selectByExample(tMarketingRelevantExample);
			responseVo.setMarketingRelevants(relevantList);
		}
		if (coupon.getReceiveStartTime().after(new Date())) {
			responseVo.setConponStatus(MarketingCouponStatusEnum.UN_START.getType());
		} else if (coupon.getReceiveEndTime().before(new Date())) {
			responseVo.setConponStatus(MarketingCouponStatusEnum.OVER.getType());
		} else {
			responseVo.setConponStatus(MarketingCouponStatusEnum.RUNING.getType());
		}
		StringBuffer daysInfo = new StringBuffer();
		if (StringUtils.isNotBlank(coupon.getWeekHourIds()) && (!"0".equals(coupon.getWeekHourIds()))) {
			TActivityDaysExample example = new TActivityDaysExample();
			example.createCriteria().andActivityIdEqualTo(couponTemplateId)
					.andActivityTypeEqualTo(coupon.getMarketingType()).andStatusEqualTo(Constant.STATUS_YES);
			List<TActivityDays> activityDaysList = tActivityDaysMapper.selectByExample(example);
			List<ActivityDaysResponseVo> activityDaysResponseList = new ArrayList<ActivityDaysResponseVo>();
			if (CollectionUtils.isEmpty(activityDaysList)) {
				return ResponseMessage.ok(responseVo);
			}
			int size = activityDaysList.size();
			for (int i = 0; i < size; i++) {
				TActivityDays activityDays = activityDaysList.get(i);
				ActivityDaysResponseVo vo = new ActivityDaysResponseVo();
				BeanUtils.copyProperties(activityDays, vo);
				activityDaysResponseList.add(vo);
				String days = activityDays.getDayids();
				if (days.startsWith(",")) {
					days = days.substring(1, days.length());
				}
				if (days.endsWith(",")) {
					days = days.substring(0, days.length() - 1);
				}
				daysInfo.append(WeekUtil.convertWeek(days)).append(", ")
						.append(DateUtils.formatDate(activityDays.getStartTime(), DateUtils.TIME_FORMAT)).append("~")
						.append(DateUtils.formatDate(activityDays.getEndTime(), DateUtils.TIME_FORMAT)).append("; ");
			}
			responseVo.setActivityDays(activityDaysResponseList);
		} else {
			//daysInfo.append("日期: 周一至周日; 时间: 0:00 ~ 24:00;");
			daysInfo.append("无限制;");
		}
		responseVo.setDayMemo(daysInfo.toString());
		return ResponseMessage.ok(responseVo);
	}

	@Override
	public ResponseMessage queryCouponByTemplate(MarketingParam couponTemplateExample) {
		TMarketingCouponExample example = new TMarketingCouponExample();
		com.xingkeduo.model.example.TMarketingCouponExample.Criteria criteria = example.createCriteria();
		if (couponTemplateExample.getMarketingType() != null) {
			criteria.andMarketingTypeEqualTo(couponTemplateExample.getMarketingType());
		}
		// 券Id,券名称
		if (StringUtils.isNumeric(couponTemplateExample.getMarketingInfo())) {
			criteria.andIdEqualTo(Long.valueOf(couponTemplateExample.getMarketingInfo()));
		} else if (StringUtils.isNotBlank(couponTemplateExample.getMarketingInfo())) {
			criteria.andNameLike("%" + couponTemplateExample.getMarketingInfo() + "%");
		}
		// 券类型
		if (StringUtils.isNotBlank(couponTemplateExample.getServiceType())) {
			criteria.andServiceTypeEqualTo(couponTemplateExample.getServiceType());
		}
		// 适用服务
		if (StringUtils.isNotBlank(couponTemplateExample.getSupportServprodIds())) {
			criteria.andSupportServprodIdsLike("%," + couponTemplateExample.getSupportServprodIds() + ",%");
		}
		// 领取范围
		if (couponTemplateExample.getReceiveType() != null) {
			criteria.andReceiveTypeEqualTo(couponTemplateExample.getReceiveType());
		}
		// 适用门店
		if (StringUtils.isNotBlank(couponTemplateExample.getStoreIds())) {
			criteria.andStoreIdsLike("%," + couponTemplateExample.getStoreIds() + ",%");
		}
		// 券状态
		if (StringUtils.isNotBlank(couponTemplateExample.getConponStatus())) {
			MarketingCouponStatusEnum marketCouponStatusEnum = MarketingCouponStatusEnum
					.parse(couponTemplateExample.getConponStatus());
			switch (marketCouponStatusEnum) {
			case UN_START:// 未开始˙
				criteria.andReceiveStartTimeGreaterThan(new Date());
				break;
			case RUNING:// 进行中
				criteria.andReceiveStartTimeLessThan(new Date());
				criteria.andReceiveEndTimeGreaterThan(new Date());
				break;
			case OVER:// 已结束
				criteria.andReceiveEndTimeLessThan(new Date());
				break;
			default:
				break;
			}
		}
		// 上下架
		if (couponTemplateExample.getStatus() != null) {
			criteria.andStatusEqualTo(couponTemplateExample.getStatus());
		}
		// 全部是否开启兑换码
		if (couponTemplateExample.getIsOpenConvert() != null) {
			criteria.andIsOpenConvertEqualTo(couponTemplateExample.getIsOpenConvert());
		}
		example.setOrderByClause(" id desc");
		PageHelper.startPage(couponTemplateExample.getPageNum(), couponTemplateExample.getPageSize());
		List<TMarketingCouponWithBLOBs> couponList = tMarketingCouponMapper.selectByExampleWithBLOBs(example);
		PageInfo<TMarketingCouponWithBLOBs> page = new PageInfo<>(couponList);
		return ResponseMessage.ok(page);
	}

	@Override
	public ResponseMessage updateCouponStatusById(MarketingParam couponTemplate) {
		TMarketingCouponWithBLOBs coupon = new TMarketingCouponWithBLOBs();
		coupon.setId(couponTemplate.getId());
		coupon.setStatus(couponTemplate.getStatus());
		coupon.setUpdateBy(couponTemplate.getUpdateBy());
		coupon.setUpdateTime(new Date());
		tMarketingCouponMapper.updateByPrimaryKeySelective(coupon);
		return ResponseMessage.ok("修改状态成功");
	}

	@Override
	public ResponseMessage getAllCouponTemplateList(MarketingParam couponTemplateExample) {
		TMarketingCouponExample example = new TMarketingCouponExample();
		Criteria criteria = example.createCriteria();
		criteria.andMarketingTypeEqualTo(couponTemplateExample.getMarketingType()).andStatusEqualTo(Constant.STATUS_YES)
				.andReceiveEndTimeGreaterThanOrEqualTo(new Date());
		if (StringUtils.isNotBlank(couponTemplateExample.getServiceType())) {
			criteria.andServiceTypeEqualTo(couponTemplateExample.getServiceType());
		}
		example.setOrderByClause(" id desc");
		List<TMarketingCouponWithBLOBs> couponList = tMarketingCouponMapper.selectByExampleWithBLOBs(example);
		if(CollectionUtils.isEmpty(couponList)) {
			return ResponseMessage.ok(new ArrayList<>());
		}
		List<Map> resultList = Lists.transform(couponList, new Function<TMarketingCouponWithBLOBs, Map>() {
			@Override
			public Map apply(TMarketingCouponWithBLOBs input) {
				Map map = new HashMap();
				map.put("id", input.getId());
				map.put("name", input.getName());
				map.put("memo", input.getId()+"_"+input.getName());
				if(0==input.getUseType()) {
					map.put("memoCustomer", input.getId()+"_"+input.getName()+"_领取后"+input.getUsePeriod()+"天可用");
				}
				if(1==input.getUseType()) {
					map.put("memoCustomer", input.getId()+"_"+input.getName()+"_"+DateUtils.formatDate(input.getUseStartTime(), DateUtils.DATE_FORMAT)+"~"+DateUtils.formatDate(input.getUseEndTime(), DateUtils.DATE_FORMAT)+"可用");
				}
				return map;
			}
		});
		return ResponseMessage.ok(resultList);
	}
}
